package com.demo.swingquickticket.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.swingquickticket.entity.User;
import com.demo.swingquickticket.util.http.HttpClientUtils;
import com.demo.swingquickticket.util.http.HttpContents;
import com.demo.swingquickticket.util.http.RequestEntity;
import com.demo.swingquickticket.util.http.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ContactService {

    public List<User> getUsers() {
        List<User> users = new ArrayList<>();
        RequestEntity request = new RequestEntity("https://kyfw.12306.cn/otn/passengers/query", HttpContents.POST_TYPE);
        request.setCookieList(DataService.getAccount().getLoginCookie());
        request.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        request.addParam("pageIndex", "1");
        request.addParam("pageSize", "9999");
        request.buildHttpClient();
        ResponseEntity response = HttpClientUtils.doRequest(request);
        JSONObject userJSON = JSONObject.parseObject(response.getResult());
        if (userJSON.getBoolean("status")) {
            JSONArray userJSONs = userJSON.getJSONObject("data").getJSONArray("datas");
            for (int i = 0; i < userJSONs.size(); i++) {
                JSONObject temp = userJSONs.getJSONObject(i);
                User user = new User();
                user.setName(temp.getString("passenger_name"));
                user.setIdType(temp.getString("passenger_id_type_code"));
                user.setId(temp.getString("passenger_id_no"));
                user.setPhone(temp.getString("mobile_no"));
                user.setTicketType(temp.getString("passenger_type"));
                users.add(user);
            }
        }
        return users;
    }

    public void addUser(String name, String idType, String id, String phone, String ticketType) {

    }

    public void delUser(String name, String idType, String id) {
        RequestEntity request = new RequestEntity("https://kyfw.12306.cn/otn/passengers/delete", HttpContents.POST_TYPE);
        request.setCookieList(DataService.getAccount().getLoginCookie());
        request.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        request.addParam("isUserSelf", "N");
        request.addParam("passenger_id_no", id + "#");
        request.addParam("passenger_id_type_code", idType);
        request.addParam("passenger_name", name + "#");
        request.buildHttpClient();
        ResponseEntity response = HttpClientUtils.doRequest(request);
        System.out.println(response);
    }
}
